<?php
/**
 * Author: Administrator
 * Date: 2022/7/20 0:10
 */

namespace DesignPatterns\Structural\DataMapper;


class UserMapper
{
    /**
     * @var DBAL
     */
    protected $db;
    public function __construct(DBAL $db)
    {
        $this->db = $db;
    }

    public function save(User $user) {
        $data = array(
            'name' => $user->getName(),
            'email' => $user->getEmail()
        );
        if ($id = $user->getId()) {
            return $this->db->update($data, ['id' => $id]);
        } else {
            return $this->db->insert($data);
        }
    }

    public function findById($id) {
        $result = $this->db->find($id);
        if (count($result)) {
            return $this->mapObject($result->current());
        } else {
//            return null;
            throw new \InvalidArgumentException('User #'.$id. ' not found'); // for testing
        }
    }

    public function findAll() {
        $result = $this->db->findAll();
        $ret = [];
        foreach($result as $r) {
            $ret[] = $this->mapObject($r);
        }
        return $ret;
    }

    protected function mapObject($row) {
        return new User($row['id'], $row['name'], $row['email']);
    }
}